from typing import List
from .model import ProductGroup
from ninja import Field, ModelSchema, Query, Router
from ninja.pagination import paginate
from utils.fu_crud import (
    ImportSchema,
    create,
    delete,
    export_data,
    import_data,
    retrieve,
    update,
)
from utils.fu_ninja import FuFilters, MyPagination

router = Router()


# 设置过滤字段
class Filters(FuFilters):
        
    name: str = Field(None, alias='name')    
    product_group: str = Field(None, alias='product_group')


# 设置请求接收字段
class ProductGroupSchemaIn(ModelSchema):

    class Config:
        model = ProductGroup
        model_exclude = ['creation_on', 'change_on',  'change_by', 'creation_by', 'product_group']


# 设置响应字段
class ProductGroupSchemaOut(ModelSchema):

    class Config:
        model = ProductGroup
        model_fields = '__all__'


# 创建ProductGroup
@router.post('/product_group', response=ProductGroupSchemaOut)
def create_product_group(request, data: ProductGroupSchemaIn):
    product_group = create(request, data, ProductGroup)
    return product_group


# 删除ProductGroup
@router.delete('/product_group/{id}')
def delete_product_group(request, id: int):
    delete(id, ProductGroup)
    return {'success': True}


# 更新ProductGroup
@router.put('/product_group/{id}', response=ProductGroupSchemaOut)
def update_product_group(request, id: int, data: ProductGroupSchemaIn):
    product_group = update(request, id, data, ProductGroup)
    return product_group


# 获取ProductGroup
@router.get('/product_group', response=List[ProductGroupSchemaOut])
@paginate(MyPagination)
def list_product_group(request, filters: Filters = Query(...)):
    qs = retrieve(request, ProductGroup, filters)
    return qs


# 导入
@router.get('/product_group/all/export')
def export_product_group(request):
    export_fields = ('name', 'product_group', )
    return export_data(request, ProductGroup, ProductGroupSchemaOut, export_fields)


# 导出
@router.post('/product_group/all/import')
def import_product_group(request, data: ImportSchema):
    import_fields = ('name', 'product_group', )
    return import_data(request, ProductGroup, ProductGroupSchemaIn, data, import_fields)
    